﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;


namespace ThermostatMonitorLib
{
    public partial class OutsideConditions
    {
        public static OutsideConditions LoadRange(int locationId, DateTime startDate, DateTime endDate)
        {
            return OutsideConditions.LoadOutsideConditions("SELECT * FROM OutsideConditions WHERE LocationId=@LocationId AND LogDate BETWEEN @StartDate and @EndDate", CommandType.Text, new SqlParameter[] { new SqlParameter("@LocationId", locationId), new SqlParameter("@StartDate", startDate), new SqlParameter("@EndDate", endDate) });
        }

        public static DataTable LoadSummary(int locationId, DateTime startDate, DateTime endDate, int timezoneDifference)
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT CONVERT(varchar, DateAdd(hh," + timezoneDifference.ToString() + ",LogDate), 101) as LogDate,MIN(Degrees) as MinDegrees,MAX(Degrees) as MaxDegrees FROM OutsideConditions WHERE LocationId=@LocationId AND DateAdd(hh," + timezoneDifference.ToString() + ",LogDate) BETWEEN @StartDate AND @EndDate GROUP BY CONVERT(varchar, DateAdd(hh," + timezoneDifference.ToString() + ",LogDate), 101)", Global.Connection);
            adapter.SelectCommand.Parameters.AddWithValue("@LocationId", locationId);
            adapter.SelectCommand.Parameters.AddWithValue("@StartDate", startDate.Date);
            adapter.SelectCommand.Parameters.AddWithValue("@EndDate", endDate.Date.AddDays(1).AddMilliseconds(-1));
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            return dt;
        }

        public string GetCSV()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("LogDate", typeof(DateTime));
            dt.Columns.Add("Degrees", typeof(int));
            foreach (OutsideCondition cond in this)
            {
                DataRow row = dt.NewRow();
                row["LogDate"] = cond.LogDate;
                row["Degrees"] = cond.Degrees;
                dt.Rows.Add(row);
            }
            return Utils.DataTableToCSV(dt);
        }

        public OutsideCondition GetByTime(DateTime time)
        {
            OutsideCondition result = null;
            foreach (ThermostatMonitorLib.OutsideCondition c in this)
            {
                if (c.LogDate <= time) result = c;
            }
            return result;
        }

    }
}
